<?php

namespace Frieza\Modules\Position\Controllers;

use Encore\Admin\Grid;
use Doraemon\tools\Area;
use Doraemon\model\Phone;
use Doraemon\model\Blank;
use Doraemon\model\Badge;
use Doraemon\model\Member;
use Biz\model\brand\Brand;
use Doraemon\tools\HhzEnv;
use Doraemon\model\Article;
use Doraemon\model\Comment;
use Illuminate\Http\Request;
use App\Pockets\GridDataModel;
use Doraemon\cache\UserCounter;
use Encore\Admin\Facades\Admin;
use Doraemon\model\AdmUserType;
use Encore\Admin\Layout\Content;
use Biz\pockets\excel\DownExcel;
use Doraemon\service\User as sUser;
use Doraemon\service\CommonEmblem;
use Hhz\AdministrativeRegion\Region;
use App\Http\Controllers\Controller;
use Doraemon\service\Member as sMember;
use Doraemon\service\Member\PhoneCrypto;
use Frieza\Modules\Position\Actions\Frozen;
use Frieza\Modules\Position\Actions\Approve;
use Frieza\Modules\Position\Actions\UserRate;
use Doraemon\model\AdmUserType as mAdmUserType;
use Frieza\Modules\Position\Actions\NickWhite;
use Frieza\Modules\Position\Actions\MessageLog;
use Frieza\Modules\Position\Actions\SaleUnbind;
use Frieza\Modules\Position\Actions\ChangePhone;
use Frieza\Modules\Position\Actions\OperateLogo;
use Frieza\Modules\Position\Actions\SendMessage;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Frieza\Modules\Position\Actions\CancelFrozen;
use Frieza\Modules\Position\Actions\ForbiddenUser;
use Frieza\Modules\Position\Actions\CancelApprove;
use Frieza\Modules\Position\Actions\ChangeUsername;
use Frieza\Modules\Position\Actions\SaleBindAction;
use Frieza\Modules\Position\Actions\ClearPhoneCache;
use Frieza\Modules\Position\Actions\CancelForbidden;
use Frieza\Modules\Position\Actions\BrandChangeArea;
use Frieza\Modules\Position\Actions\DeleteUserCache;
use Frieza\Modules\Position\Actions\SetUnAuthDesigner;
use Doraemon\service\position\Search\AdUserProfileList;
use Doraemon\service\position\Search\UserFilterSchedule;
use Frieza\Modules\Position\Actions\CancelUnauthDesigner;
use Frieza\Modules\Position\Actions\ClearIdentifyingCodeCache;

class UserProfileListController extends Controller
{
    public static $badge = [
        1013010 => '居住榜样',
        1014010 => '绿植能手',
        1015010 => '插花能手',
        1016010 => '家务能手',
        1017010 => 'DIY能手',
        1018010 => '收纳能手',
    ];

    public static $product_level = [
        10 => '全部',
        0 => 'L0',
        1 => 'L1',
        2 => 'L2',
        3 => 'L3',
        4 => 'L4',
        5 => 'L5',
        6 => 'L6',
        7 => 'L7',
        8 => 'L8',
        9 => 'L9'
    ];
    public static $product_level_new = [
        0 => 'Lv0',
        1 => 'Lv1',
        2 => 'Lv2',
        3 => 'Lv3',
        4 => 'Lv4',
        5 => 'Lv5',
        6 => 'Lv6',
        7 => 'Lv7',
    ];

    const PAGE_SIZE = 20;
    public static $a_find_type = array(
        0 => "uid",
        1 => "昵称",
        2 => "电话号码",
    );

    public function __construct()
    {
        parent::__construct();
        Admin::script(
<<<EOF
$('input[type=radio][name=select_area]').on('ifChecked',function(){
    if(this.value == 1) {
        $("select.multiplearea").parent().parent().hide();
        $("select.province").parent().parent().show();
        $("select.city").parent().parent().show();
    }else {
        $("select.multiplearea").parent().parent().show();
        $("select.city").parent().parent().hide();
        $("select.province").parent().parent().hide();
    }
});
$('input[type=radio][name=select_area]:checked').trigger('ifChecked');
EOF
        );
    }

    public function index(Request $request, Content $content)
    {
        $url = $_SERVER["REQUEST_URI"];
        $data_url = explode('?',$url);
        if(!isset($request['select_area'])) {
            $request['select_area'] = "1";
        }
        if($request['select_area'] == 1){
            $request['multiplearea'] = [];
        } elseif($request['select_area'] == 0){
            $request['city'] = '';
        }
        $request = $request->all();
        $province_id = '';
        if ($request['select_area'] == 1){
            $province_id = $request['province'] ?? '';
        }
        $export_url = $data_url[1];
        $page = isset($request['page']) ? $request['page'] : 1;
        $pageSize = isset($request['per_page']) ? $request['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        $request['LIMIT'] = $limit;
        $params = new AdUserProfileList($request);
        $result_data = UserFilterSchedule::search($params);
        // fix Find搜索调条件二次点击搜索后，添加选项又恢复为默认uid的bug
        $i_find_group = isset($request['Find_group']) ? $request['Find_group'] : 0 ;
        $s_find_group_value = self::$a_find_type[$i_find_group];
        Admin::script(
<<<EOF
$(".Find-filter-group-label").text("{$s_find_group_value}");
$(".Find-filter-group-operation").val({$i_find_group});
EOF
        );
        $row = $result_data['rows'];
        $uids = [];
        $userdata = [];

        if (HhzEnv::isTest()) {
            $search = [];
            if($request['Find_group'] == 0 && !empty($request['Find'])){
                $search = ['uid' =>$request['Find']];
            }elseif($request['Find_group'] == 1 && !empty($request['Find'])){
                $search = ['nick' =>$request['Find']];
            }elseif($request['Find_group'] == 2 && !empty($request['Find'])){
                $encrypt_phone = PhoneCrypto::encrypt($request['Find'],PhoneCrypto::CLIENT_YAPI,PhoneCrypto::VERSIN);
                $uid = Phone::getUidByPhone($encrypt_phone);
                if($uid) {
                    $search = ['uid' => $uid];
                }
            }

            $list = sMember::getMemberList($page, $pageSize, $search);
            $row = $list['list'];
            $result_data['total'] = $list['total'];
        }
        if (!empty($row)){
            foreach ($row as $key => &$value){
                $userdata[$value['uid']] = $value;
                array_push($uids,$value['uid']);
            }
            $userinfos = self::GetUidInfo($uids,$userdata);
            $list = $userinfos;
            $subject['list'] = $list;
            $subject['total'] = $result_data['total'];
        }else{
            $subject['list'] = $row;
            $subject['total'] = $result_data['total'];
        }
        $export_url = $data_url[1];
        $gridModel = new GridDataModel($subject['list'], $subject['total'], [
            'perPage' => $request['per_page'] ? : $request['LIMIT'][1],
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $export_url, $province_id) {
                $grid->disableExport();
                //$grid->paginate($gridModel->getPerPage());
                $grid->tools(function ($tools) use ($export_url) {
                    $url = url('/admin/position/userProfile/exportData?'.$export_url);
                    $button = '<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" title="导出" target="_blank" href="'.$url.'"><i class="fa fa-download"></i><span class="hidden-xs"> 导出</span></a>
</div>';
                    $tools->append($button);
                });

                //筛选
                $grid->filter(function (\Encore\Admin\Grid\Filter $filter) use ($province_id){
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();

                    $filter->column(1/2, function ($filter) {
                        $filter->group('Find', function ($group) {
                            $group->equal('uid');
                            $group->equal('昵称');
                            $group->equal('电话号码');
                        });
                        $filter->equal('user_type', '用户身份')->checkbox(Member::$typeDesc);
                        $filter->equal('user_tag', '用户标识')->checkbox([0 => '无标识', mAdmUserType::AUTH_TAG_SUSPECTED_BUSINESS => '疑似商业用户', mAdmUserType::AUTH_TAG_WAIT_BRAND => '待认证品牌']);
                        $filter->equal('quality', '用户质量')->checkbox([0 => '无', mAdmUserType::B1 => 'B1', mAdmUserType::B2 => 'B2', mAdmUserType::B3 => 'B3', mAdmUserType::XL => 'XL']);
                        $filter->equal('badge_name', '用户徽章')->checkbox(['居住榜样' => '居住榜样', '收纳能手' => '收纳能手', '家务能手' => '家务能手', 'DIY能手' => 'DIY能手', '绿植能手' => '绿植能手', '插花能手' => '插花能手']);
//                        $filter->equal('user_product_level', '用户生产等级')->checkbox(self::$product_level);
                        $filter->equal('product_level', '用户生产等级')->checkbox(self::$product_level_new);
                        $filter->between('register_time', '注册时间')->date();
                        $filter->between('last_login_day', '最后使用时间')->date();
                        $filter->between('last_product_time', '最后生产时间')->date();
                        $filter->between('note_num', 'note数');
                    });

                    $filter->column(1/2, function ($filter) use ($province_id) {
                        $filter->between('article_num', '整屋数');
                        $filter->between('blank_num', '文章数');
                        $filter->between('interaction_num', '主动交互数');//包括赞+收藏+评论+分享
                        $filter->between('belikefav_num', '获赞与收藏数');
                        $filter->between('becomment_count', '被评论数');
                        $filter->between('fans_num', '被关注数');//粉丝数

                        $top = Region::getProvincesList();
                        $filter->equal('select_area', '地区')->radio([
                            0 => '地区多选(支持到省和直辖市)',
                            1 => '地区单查(支持到市、区)',
                        ])->default("110100");
                        $filter->in('multiplearea', '地区(多选)')->multipleSelect($top);
                        $filter->equal('province', '省')->select($top)->load('city',
                            '/admin/extend/area/get');
                        $all_city = Region::getCityListByProvinceCode((string)$province_id);
                        $filter->equal('city', '市/区')->select($all_city);
                        $filter->equal('login_weeks_include_this_week', '连续周启动')->checkbox([0 => '2周', 1 => '3周', 2 => '4周', 3 => '5周及5周以上']);
                    });

                    //连读登录周数区分这两个字段:
                    //login_weeks_include_this_week 最近1年连续登录周数(包含本周 )
                    //login_weeks_exclude_this_week 最近1年连续登录周数(不包含本周 )
                    //fans_num 被关注数，粉丝数
                    //被收藏是这个: befaved_num
                    //获赞是这个:beliked_num
                    //被评论是这个:becomment_count

                    //条件展开
                    $filter->expand();

                });
                $grid->disableCreateButton();
                //$grid->disableActions();
                $grid->setActionClass(DropdownActions::class);
                //$grid->setActionClass(ContextMenuActions::class);
                $grid->disableRowSelector();
                $grid->perPages([10, 20, 30, 40, 50, 100, 500, 1000, 2000, 5000]);
                //$grid->disablePagination();
                $grid->column('avatar', '头像')->display(function(){
                    return '<img src = "'.$this->avatar.'" width = 45px height = 45px />';
                });;
                $grid->column('nick', '昵称');
                $grid->column('uid', 'uid')->sortable()->display(function() {
                    return "<a href='/admin/user/Detail/$this->uid' target='_blank' >".$this->uid."</a>";
                })->width(100)->copyable();
                $grid->column('type', '用户身份');
                $grid->column('user_tag', '用户标识');
                $grid->column('quality', '用户质量');
//                $grid->column('user_product_level', '用户生产等级');
                $grid->column('product_level', '用户生产等级');
                $grid->column('register_time', '注册时间')->sortable();
                $grid->column('last_login_day', '最后使用时间')->sortable();
                $grid->column('last_product_time', '最后生产时间')->sortable();
                $grid->column('note_num', 'note数')->sortable()->display(function() {
                    return "<a href='/admin/photo/photoList/index?show_type=1&is_consume=2&uid=$this->uid' target='_blank' >".$this->note_num."</a>";
                })->width(100);
                $grid->column('article_num', '整屋数')->sortable()->display(function() {
                    return "<a href='/admin/article/ArticleList/index?&uid=$this->uid' target='_blank' >".$this->article_num."</a>";
                })->width(100);
                $grid->column('blank_num', '文章数')->sortable()->display(function() {
                    return "<a href='/admin/blank/BlankList/index?&uid=$this->uid' target='_blank' >".$this->blank_num."</a>";
                })->width(100);
                $grid->column('interaction_num', '主动交互数')->sortable();
                $grid->column('belikefav_num', '获赞与收藏数')->sortable();
                $grid->column('becomment_count', '被评论数')->sortable();
                $grid->column('fans', '被关注数')->sortable();
                $grid->column('area_name', '地区');
                $grid->column('login_weeks_include_this_week', '连续周启动');
                $grid->column('badge_name', '用户徽章');
                $grid->actions(function (Grid\Displayers\Actions $actions){
                    //dd($uid);
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();
                    $uid = $actions->row->id;
                    $user_info = Member::getUserInfo($uid);
                    //dd($user_info);
                    $actions->add(new OperateLogo);
                    //处理认证的情况(1.普通用户存在认证;2.已经认证为个人V和机构V的用户应该是取消认证)
                    if ($user_info['type'] == Member::USER_COMMON){
                        $actions->add(new Approve);
                        //这个操作只有韩丽凡,张志杰,胡京东可见
                        if (in_array(Admin::user()->username,['hanlifan','zhangzhijie','hujingdong'])){
                            $actions->add(new SetUnAuthDesigner);
                        }
                    }elseif($user_info['type'] == Member::AUTH_USER_V || $user_info['type'] == Member::AUTH_ORG_V){
                        $actions->add(new CancelApprove);
                    }elseif ($user_info['type'] == Member::AUTH_USER_BRAND){
                        $actions->add(new BrandChangeArea);
                    }elseif ($user_info['type'] == Member::AUTH_USER_UNAUTH_DESIGNER){
                        $actions->add(new CancelUnauthDesigner);
                    }
                    //处理冻结的情况(如果用户已经被冻结则是取消冻结的方法)
                    $status = $user_info['status'];
                    if ($status == Member::STATUS_FROZEN){
                        $actions->add(new CancelFrozen);
                    }else{
                        $actions->add(new Frozen);
                    }
                    $actions->add(new UserRate);
                    //处理封禁的情况(如果用户已经被封禁的话 则是取消封禁的方法)
                    if ($status == Member::STATUS_BLOCKED){
                        $actions->add(new CancelForbidden);
                    }else{
                        $actions->add(new ForbiddenUser);
                    }
                    $actions->add(new ChangeUsername);
                    $actions->add(new NickWhite);
                    $actions->add(new SendMessage);
                    $actions->add(new MessageLog);
//                    $phone = Phone::getUserPhone($uid);
                    $phoneInfo = Phone::getByUid($uid);
                    $phone = $phoneInfo['phone'];
                    if (!empty($phone)) { //如果有手机号的时候直接清理缓存，没有的话需要输入手机号清理
                        $actions->add(new ClearIdentifyingCodeCache);
                    } else {
                        $actions->add(new ClearPhoneCache);
                    }

                    $actions->add(new DeleteUserCache);
                    // 白名单
                    if (in_array(Admin::user()->username,['sunchengwei','zhouchao','zhangzhijie','xinshaopu','yuanqianpeng'])) {
                        $actions->add(new ChangePhone);
                    }
                    $actions->add(new SaleBindAction);
                    $actions->add(new SaleUnbind);


                });

//                $grid->actions(function (Grid\Displayers\Actions $actions) use ($uid) {
//                    $actions->disableEdit();
//                    $actions->disableDelete();
//                    $actions->disableView();
//                    if ($actions->row->info_id > 0) {
//                        $actions->prepend('<a class="fa fa-remove reload-data" data-uid="' . $uid . '" data-info_id="' . $actions->row->info_id . '" data-position_id="' . $actions->row->position_id . '" href="javascript:void(0);")>清除缓存</a>');
//                    }
//                });
            });

//        $url = url($link);
//        $content->row("<a href = '.$url.' target = '_blank' >导出数据</a>");
        //$content->row(new UserButton(UserButton::TYPE_HREF, '', '导出数据', '', url('/admin/position/userProfile/exportData?'.$export_url)));
        return $content
            ->header('用户分群查询')
            ->description(' ')
            ->breadcrumb(['text' => '用户分群查询'])
            ->row($gridList);
    }

    public function GetUidInfo($uids,$userdata){
        $userInfos = sMember::getUserInfoByUserIds($uids);
        $userInfos = array_replace(array_flip($uids), $userInfos);
        $userinfo = [];
        foreach ($userInfos as $k => $info){
            $alluserdata['id'] = $info['uid'];
            $alluserdata['uid'] = $info['uid'];
            $alluserdata['nick'] = $info['nick'];
            $alluserdata['avatar'] = $info['avatar'];
            $alluserdata['type'] = self::FormateType($k,$info['type']);
            $alluserdata['area'] = $info['area_name'] ?? ''; //地区名称
            $alluserdata['area_name'] = $info['area_name'] ?? ''; //地区名称
            $adm_info = self::FormateUserTag($k);
            $alluserdata['user_tag'] = $adm_info['user_tag'];
            $alluserdata['quality'] = $adm_info['user_quality'];
//            $alluserdata['user_product_level'] = $userdata[$k]['user_product_level'];
            $alluserdata['product_level'] = $userdata[$k]['product_level'];
            $alluserdata['register_time'] = date("Y-m-d", $info['addtime']);
            $user_time = self::FormatLastProTime($k,$userdata[$k]['last_login_time']);
            $alluserdata['last_product_time'] = $user_time['lastReleaseTime'];
            $alluserdata['last_login_day'] = $user_time['lastLoginTime'];
            $counter = self::FormateUserCounter($k,$userdata[$k]['share']);
            $alluserdata['note_num'] = $counter['photos'];
            $alluserdata['article_num'] = $counter['articles'];
            $alluserdata['blank_num'] = $counter['blanks'];
            $alluserdata['interaction_num'] = $counter['interaction_num'];
            $alluserdata['belikefav_num'] = $counter['belikefav_num'];
            $alluserdata['becomment_count'] = $userdata[$k]['becomment_num'];
            $alluserdata['fans'] = $counter['fans'];
            $alluserdata['login_weeks_include_this_week'] = self::FormateWeek($userdata[$k]['week']);
            $alluserdata['badge_name'] = self::FormateBadge($k);
            array_push($userinfo,$alluserdata);
        }
        return $userinfo;
    }

    public function FormateType($uid,$type){
        $all_type = Member::$typeDesc;
        foreach ($all_type as $key => $value){
            if ($type == Member::AUTH_USER_BRAND){
                $brand_type = sUser::getBrandInfo($uid)['type'];
                if ($brand_type == Brand::TYPE_BRAND){
                    $type = '认证品牌';
                }elseif ($brand_type == Brand::TYPE_SHOP){
                    $type = '认证店铺';
                }
            }elseif($type == $key) {
                $type = $value;
            }
        }

        return $type;
    }


    public function FormateUserTag($uid){
        $adm_tag = AdmUserType::getById($uid);
        $adm_userInfo = [];
        if (is_array($adm_tag)){
            $user_tag = $adm_tag['auth_tag'];
            $user_quality = $adm_tag['quality'];
            if ($user_tag == AdmUserType::AUTH_TAG_SUSPECTED_BUSINESS){
                $adm_userInfo['user_tag'] = '疑似商业用户';
            }elseif ($user_tag == AdmUserType::AUTH_TAG_WAIT_BRAND){
                $adm_userInfo['user_tag'] = '待认证品牌';
            }else{
                $adm_userInfo['user_tag'] = '无';
            }
            if ($user_quality == AdmUserType::B1){
                $adm_userInfo['user_quality'] = "B1用户";
            }elseif ($user_quality == AdmUserType::B2){
                $adm_userInfo['user_quality'] = "B2用户";
            }elseif ($user_quality == AdmUserType::B3){
                $adm_userInfo['user_quality'] = "B3用户";
            }elseif ($user_quality == AdmUserType::XL){
                $adm_userInfo['user_quality'] = "XL用户";
            }else{
                $adm_userInfo['user_quality'] = "无";
            }
        }else {
            $adm_userInfo['user_quality'] = "无";
            $adm_userInfo['user_tag'] = '无';
        }
        return $adm_userInfo;
    }

    public function FormatLastProTime($uid,$last_login_time){
        $lastReleaseTime = CommonEmblem::getLastReleaseDays($uid);
        $user_time = [];
        $user_time['lastReleaseTime'] = self::timeFormat($lastReleaseTime);
        //$last_login_day = RedisCache::getLoginTime($uid);
        $last_login_day = $last_login_time;
        if (!empty($last_login_day)){
            $user_time['lastLoginTime'] = self::timeFormat($last_login_day);
        } else {
            $user_time['lastLoginTime'] = '';
        }
        return $user_time;
    }

    protected function timeFormat($time)
    {
        if ($time) {
            $time = time() - $time;
            if ($time > 86439) {
                return floor($time / 86400) . '天前';
            } elseif ($time > 3659) {
                return floor($time / 3600) . '小时前';
            } elseif ($time > 59) {
                return floor($time / 60) . '分钟前';
            } else {
                return $time . '秒前';
            }
        } else {
            return '';
        }
    }

    public function FormateUserCounter($uid,$share_num){
        $count_arr = UserCounter::getOne($uid);
        $lists = [];
        //点赞数
        $lists['like'] = $count_arr['like'];
        //收藏数
        $lists['favorite'] = $count_arr['favorite_photo'] + $count_arr['favorite_article'] + $count_arr['favorite_guide'] + $count_arr['fav_spu'] + $count_arr['favorite_blank'] + $count_arr['favorite_answer'] + $count_arr['favorite_sitem'];
        $lists['fans'] = $count_arr['fans'];//被关注数
        $lists['beliked'] = $count_arr['beliked'];
        $lists['befavorited'] = $count_arr['befavorited'];
        $lists['photos'] = $count_arr['photos'];
        $lists['articles'] = (int)Article::getPublishCountByUid($uid);
        $lists['blanks'] = (int)Blank::getPublishCountByUid($uid);
        //评论数
        $comment_num = Comment::getUserCommentCount($uid);
        //主动交互数量
        $lists['interaction_num'] = $comment_num + $lists['like'] + $lists['favorite'] + $share_num;
        //获赞与收藏数
        $lists['belikefav_num'] = $lists['beliked'] + $lists['befavorited'];
        return $lists;
    }

    public function FormateWeek($week){
        if ($week == 2){
            return '连续两周启动';
        }elseif ($week == 3){
            return '连续三周启动';
        }elseif ($week == 4){
            return '连续四周启动';
        }elseif ($week > 4){
            $china_num = self::numToWord($week);
            return '连续'.$china_num.'周启动';
        }else{
            return '否';
        }
    }

    public function FormateBadge($uid){
        $all_badge = self::$badge;
        $is_badge = [];
        foreach ($all_badge as $badge_level_id => $badge_name){
            $is_exit = Badge::getByUidLevelId($uid,$badge_level_id);
            if ($is_exit){
                array_push($is_badge,$badge_name);
            }
        }
        if (!empty($is_badge)){
            $user_badge = implode(',',$is_badge);
            return $user_badge;
        }else{
            return '无';
        }
    }

    public function exportData(Request $request)
    {
        $request = $request->all();
        $params = new AdUserProfileList($request);
        $result_data = UserFilterSchedule::search($params);
        $row = $result_data['rows'];
        $uids = [];
        $userdata = [];
        if (!empty($row)){
            foreach ($row as $key => &$value){
                $userdata[$value['uid']] = $value;
                array_push($uids,$value['uid']);
            }
            $userinfos = self::GetUidInfo($uids,$userdata);
            $list = $userinfos;
            //dd($list);
            $subject['list'] = $list;
            $subject['total'] = $result_data['total'];
        }else{
            $subject['list'] = $row;
            $subject['total'] = $result_data['total'];
        }
        $reason = '用户分群信息';
        $header = ['ID','uid', '昵称','头像地址','用户身份','所在地区','用户标识','用户质量','用户生产等级','注册时间','最后生产时间','最后登录时间','note数','整屋数','文章数','主动交互数','获赞与收藏数','被评论数','粉丝数','连续周启动','用户徽章'];
        $letter = range('A', 'U');
        $excelObj = new DownExcel();
        $excelObj->setFileName($reason);
        $excelObj->setSheetTitle($reason);
        //设置列宽
        $widths = ['A' => 15, 'B' => 15,'C' => 25,'D' => 70,'E' => 20,'G' => 20,'J' => 20,'T' => 30];
        $excelObj->setWidth($widths);
        //默认单元格居中
        $excelObj->setDefaultStyleAlignment();
        $excelObj->freezePane('A1');//冻结窗口
        $excelObj->setTextFormat('A');
        $excelObj->setTextFormat('B');
        foreach ($header as $key => $value) {
            //设置字体
            $excelObj->setFrontName($letter[$key]);
            //设置加粗
            $excelObj->setFrontBold("$letter[$key]1");
            //设置大小
            $excelObj->setFrontSize($letter[$key]);
        }
        $excelObj->create($subject['list'], $header);
    }

    //数字转变成汉字方法
    function numToWord($num)
    {
        $chiNum = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
        $chiUni = array('','十', '百', '千', '万', '亿', '十', '百', '千');
        $chiStr = '';
        $num_str = (string)$num;
        $count = strlen($num_str);
        $last_flag = true; //上一个 是否为0
        $zero_flag = true; //是否第一个
        $temp_num = null; //临时数字
        $chiStr = '';//拼接结果
        if ($count == 2) {//两位数
            $temp_num = $num_str[0];
            $chiStr = $temp_num == 1 ? $chiUni[1] : $chiNum[$temp_num].$chiUni[1];
            $temp_num = $num_str[1];
            $chiStr .= $temp_num == 0 ? '' : $chiNum[$temp_num];
        }else if($count > 2){
            $index = 0;
            for ($i=$count-1; $i >= 0 ; $i--) {
                $temp_num = $num_str[$i];
                if ($temp_num == 0) {
                    if (!$zero_flag && !$last_flag ) {
                        $chiStr = $chiNum[$temp_num]. $chiStr;
                        $last_flag = true;
                    }
                }else{
                    $chiStr = $chiNum[$temp_num].$chiUni[$index%9] .$chiStr;
                    $zero_flag = false;
                    $last_flag = false;
                }
                $index ++;
            }
        }else{
            $chiStr = $chiNum[$num_str[0]];
        }
        return $chiStr;

    }
}
